package com.weiweiqin.controller.wechat;


import com.weiweiqin.constants.PropertyConfig;
import com.weiweiqin.weixin.util.SignUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;


@Controller
@RequestMapping(value = "/weixin")
public class WeiXinLogin {
    private static final Log LOG = LogFactory.getLog(WeiXinLogin.class);
    private static  String APPID = "";
    private static  String SECRET = "";
    private static  String URL = "";
    static {
        APPID =	PropertyConfig.getInstance().getProperty("APPID");
        SECRET = PropertyConfig.getInstance().getProperty("SECRET");
        URL = PropertyConfig.getInstance().getProperty("URL");
    }
    //请求校验（确认请求来自微信服务器）
    @RequestMapping(value = "/doGet",method = RequestMethod.GET)
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 微信加密签名
        String signature 	= request.getParameter("signature");
        // 时间戳
        String timestamp 	= request.getParameter("timestamp");
        // 随机数
        String nonce 		= request.getParameter("nonce");
        // 随机字符串
        String echostr 		= request.getParameter("echostr");
        //通过调用PrintWriter类的print()方法将处理结果respXml返回给微信服务器
        PrintWriter out = null;
        out = response.getWriter();
        // 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }
        out.close();
        out = null;
    }

    //请求校验与处理
    @RequestMapping(value = "/doGet",method = RequestMethod.POST)
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
    }

    /**
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session){

        Object customer = session.getAttribute("customer");
        if(null == customer) {
            String url  = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID+"&redirect_uri="+
                    URL+"/loginAuth"+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            return "redirect:"+url;
        }else {
            return "redirect:"+URL+"?vt"+new Date().getTime()+"#/index?auth=1";
        }

    }
}
